package juc.producerandconsumer;

/**
 * 多生产多消费synchronized实现
 * 效率慢，可能死锁
 */
public class ProCon2 {
    //描述资源类
    private String name;
    private int count=1;
    private boolean flag=false;
    public synchronized void set(String name){
        while (flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.name=name+"--"+count;
        count++;
        System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
        flag=true;
        notify();
    }
    public synchronized void get(){
        while(!flag)
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);
        flag=false;
        notify();
    }
}

class Producer2 implements Runnable{
    private ProCon2 r;
    Producer2(ProCon2 r){
        this.r=r;
    }
    @Override
    public void run(){
        while(true)
            r.set("面包");
    }
}
class Consumer2 implements Runnable{
    private ProCon2 r;
    Consumer2(ProCon2 r){
        this.r=r;
    }
    @Override
    public void run(){
        while(true)
            r.get();
    }
}
class ProducerDemo2 {
    public static void main(String[] args) {
        ProCon2 r=new ProCon2();
        Consumer2 con=new Consumer2(r);
        Producer2 pro=new Producer2(r);
        Thread t0 = new Thread(pro);
        Thread t1=new Thread(pro);
        Thread t2=new Thread(con);
        Thread t3=new Thread(con);
        t0.start();
        t1.start();
        t2.start();
        t3.start();
    }
}
